package com.todo.demo.Controller;

import com.alibaba.fastjson.JSON;
import com.todo.demo.Model.*;
import com.todo.demo.Service.LoginService;
import com.todo.demo.Service.PlanAndTaskService;
import com.todo.demo.Util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@EnableAutoConfiguration
@RequestMapping("/PLanAndTask")
public class PlanAndTaskController {
    @Autowired
    private PlanAndTaskService planAndTaskService;
    @Autowired
    private LoginService loginService;

    @RequestMapping(value = "/getPlanAndTask", method = RequestMethod.POST)
    public Object getPlanAndTask(User user) {
        if (user == null) {
            return JSON.toJSON(Util.getInstance().ResultFail("参数错误"));
        }
        List<HashMap<String, Object>> planWithTaskMap = planAndTaskService.findAllPlanWithTask(1, 100, user.getId());

        return JSON.toJSONString(planWithTaskMap);
    }

    long new_plan_id = 0;

    @RequestMapping(value = "/doSync", method = RequestMethod.POST)
    public Object doSync(String key, String userId, String user_name, String avatar_url) {
        List<PlanWithTaskFrontEnd> planWithTaskFrontEnds = JSON.parseArray(key, PlanWithTaskFrontEnd.class);

        User user = new User();
        user.setId(Long.valueOf(userId));
        user.setNick_name(user_name);
        user.setAvatar_url(avatar_url);

        User userThis = loginService.getUserById(user);
        if (userThis == null) {
            return JSON.toJSON(Util.getInstance().ResultUserNotFound("用户不存在"));
        }

        for (int x = 0; x < planWithTaskFrontEnds.size(); x++) {
            if (planWithTaskFrontEnds.get(x).getListId() == null) {

                Plan plan = new Plan();
                plan.setPlan_title(planWithTaskFrontEnds.get(x).getListName());
                try {
                    plan.setPlan_user_id(Long.valueOf(userId));
                } catch (NumberFormatException e) {
                    return JSON.toJSON(Util.getInstance().ResultFail("参数错误"));
                }

                /**
                 * 获取系统时间
                 */
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                plan.setPlan_create_time(df.format(new Date()));
                plan.setLast_edit_time(df.format(new Date()));

                new_plan_id = planAndTaskService.addPlan(plan);
            }

//            /**
//             *  在插入一条计划之后紧接着把自己也加到团队里
//             */
//            User user = new User();
//            user.setId(Long.valueOf(userId));
//
//            User userLocal = loginService.getUserById(user);
//            UserWithPlan userWithPlanFrom = new UserWithPlan();
//            userWithPlanFrom.setUser_id(Long.valueOf(userId));
//            userWithPlanFrom.setAvatar_url(userLocal.getAvatar_url());
//            userWithPlanFrom.setUser_name(userLocal.getNick_name());
//            userWithPlanFrom.setPlan_id(Long.valueOf(new_plan_id));
//
//            planAndTaskService.addUserToPlan(userWithPlanFrom);

            for (int y = 0; y < planWithTaskFrontEnds.get(x).getItem().size(); y++) {
                if (planWithTaskFrontEnds.get(x).getItem().get(y).getItemId() == null) {

                    Task task = new Task();
                    if (planWithTaskFrontEnds.get(x).getListId() == null) {
                        task.setPlan_id(new_plan_id);
                    } else {
                        task.setPlan_id(Long.valueOf(planWithTaskFrontEnds.get(x).getListId()));
                    }
                    task.setTask_title(planWithTaskFrontEnds.get(x).getItem().get(y).getItemName());
                    task.setTask_user_id(Long.valueOf(userId));

                    /**
                     * 获取系统时间
                     */
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                    task.setTask_create_time(df.format(new Date()));
                    task.setTask_last_edit_time(df.format(new Date()));

                    planAndTaskService.addTask(task);

                    /**
                     *  添加任务的时候同时去更新计划的最后编辑时间
                     */
                    Plan planForTaskAdd = new Plan();
                    planForTaskAdd.setPlan_id(task.getPlan_id());
                    planForTaskAdd.setLast_edit_time(df.format(new Date()));
                    planAndTaskService.updatePlanLastEditTime(planForTaskAdd);
                }
            }
        }

        return null;
    }

    /**
     * 划掉计划
     *
     * @param taskId
     * @param is_checked
     * @return
     */
    @RequestMapping(value = "/setTaskCheckById", method = RequestMethod.POST)
    public Object setTaskCheckById(String taskId, boolean is_checked, String userId) {
        Task planWithTaskAdd = new Task();
        planWithTaskAdd.setTask_id(Long.valueOf(taskId));
        planWithTaskAdd.setIs_checked(is_checked);
        if (userId != null)
            planWithTaskAdd.setTask_user_id(Long.valueOf(userId));

        PlanWithTask task = planAndTaskService.finTaskByTaskId(Long.valueOf(taskId));
        updateLastEditTime(task.getPlan_id());
        planAndTaskService.setTaskCheckById(planWithTaskAdd);

        User user = new User();
        user.setId(Long.valueOf(userId));

        return loginService.getUserById(user);
    }

    /**
     * 删除任务
     *
     * @param taskId
     * @return
     */
    @RequestMapping(value = "/deleteTaskById", method = RequestMethod.POST)
    public Object deleteTaskById(String taskId) {
        PlanWithTask planWithTaskAdd = new PlanWithTask();
        planWithTaskAdd.setTask_id(Long.valueOf(taskId));

        return planAndTaskService.deleteTaskById(planWithTaskAdd);
    }

    /**
     * 删除计划
     *
     * @return
     */
    @RequestMapping(value = "/deletePlanById", method = RequestMethod.POST)
    public Object deletePlanById(String planId) {
        PlanWithTask planWithTaskAdd = new PlanWithTask();
        planWithTaskAdd.setPlan_id(Long.valueOf(planId));

        updateLastEditTime(Long.valueOf(planId));
        return planAndTaskService.deletePlanById(planWithTaskAdd);
    }

    @RequestMapping(value = "/getTaskAiNum", method = RequestMethod.POST)
    public Object getTaskAiNum() {
        return planAndTaskService.getTaskAiNum();
    }

    @RequestMapping(value = "/getPlanAiNum", method = RequestMethod.POST)
    public Object getPlanAiNum() {
        return planAndTaskService.getPlanAiNum();
    }


    /**
     * 添加一个多人计划
     *
     * @param user_id
     * @param avatar_url
     * @param user_name
     * @param plan_id
     * @param fromUserId
     * @param fromUserName
     * @param from_avatar_url
     * @return
     */
    @RequestMapping(value = "/addUserToPlan", method = RequestMethod.POST)
    public Object addUserToPlan(String user_id, String avatar_url, String user_name, String plan_id, String fromUserId, String fromUserName, String from_avatar_url) {
        Plan planLocal = planAndTaskService.finPlanByPlanId(Long.valueOf(plan_id));

        /**
         *  首先先去查一下这条记录存不存在
         */
        Partner partner = new Partner();
        partner.setPlan_id(Long.valueOf(plan_id));
        partner.setUser_id(Long.valueOf(user_id));
        Partner partnerLocal = planAndTaskService.isPartakeRepeat(partner);

        if (partnerLocal == null) {
            /**
             *  被分享人
             */
            UserWithPlan userWithPlan = new UserWithPlan();
            userWithPlan.setUser_id(Long.valueOf(user_id));
            userWithPlan.setAvatar_url(avatar_url);
            userWithPlan.setUser_name(user_name);
            userWithPlan.setPlan_id(Long.valueOf(plan_id));
            userWithPlan.setCreate_user_id(planLocal.getPlan_user_id());

            /**
             * 获取系统时间
             */
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            userWithPlan.setJoin_time(df.format(new Date()));

            planAndTaskService.addUserToPlan(userWithPlan);
        }

        Partner partnerFrom = new Partner();
        partnerFrom.setPlan_id(Long.valueOf(plan_id));
        partnerFrom.setUser_id(Long.valueOf(fromUserId));
        Partner partnerFromLocal = planAndTaskService.isPartakeRepeat(partnerFrom);

        if (partnerFromLocal == null) {
            /**
             *  分享人
             */
            UserWithPlan userWithPlanFrom = new UserWithPlan();
            userWithPlanFrom.setUser_id(Long.valueOf(fromUserId));
            userWithPlanFrom.setAvatar_url(from_avatar_url);
            userWithPlanFrom.setUser_name(fromUserName);
            userWithPlanFrom.setPlan_id(Long.valueOf(plan_id));
            userWithPlanFrom.setCreate_user_id(planLocal.getPlan_user_id());

            /**
             * 如果是分享人并且这张表里没有这个人的时候就存0
             * 让他永远在第一个
             */
            userWithPlanFrom.setJoin_time("0");
            planAndTaskService.addUserToPlan(userWithPlanFrom);
        }

        /**
         *  先把用户分享出的这条计划查出来
         *  用于拼接parnters字段
         */
        if (planLocal.getParnters() == null)
            planLocal.setParnters("");
        String parnterLocal = planLocal.getParnters();
        if (parnterLocal.isEmpty() || parnterLocal.equals("")) {
            parnterLocal = user_id;
        } else {
            parnterLocal = parnterLocal + "," + Long.valueOf(user_id);
        }

        /**
         *  对方同意加入之后更新这条计划的type为1
         *  将对方加入到自己计划的parnter中
         */
        Plan plan = new Plan();
        plan.setPlan_id(Long.valueOf(plan_id));
        plan.setPlan_type(1);
        plan.setParnters(parnterLocal);

        planAndTaskService.updateTypeIdForPLan(plan);

        return 1;
    }

    @RequestMapping(value = "/getPartnerByPlanId", method = RequestMethod.POST)
    public Object getPartnerByPlanId(String planId) {
        Partner partner = new Partner();
        partner.setPlan_id(Long.valueOf(planId));

        List<Partner> partners = planAndTaskService.getPartnerByPlanId(partner);

        return JSON.toJSONString(partners);
    }

    @RequestMapping(value = "/quitPartake", method = RequestMethod.POST)
    public Object quitPartake(String planId, String user_id) {
        /**
         *  先把用户分享出的这条计划查出来
         *  用于拼接parnters字段
         */
        Plan planLocal = planAndTaskService.finPlanByPlanId(Long.valueOf(planId));
        if (planLocal.getPlan_user_id() == Long.valueOf(user_id)) {
            return JSON.toJSON(Util.getInstance().ResultFail("计划创建人无法退出团队"));
        }

        Partner partner = new Partner();
        partner.setPlan_id(Long.valueOf(planId));
        partner.setUser_id(Long.valueOf(user_id));
        planAndTaskService.quitPartake(partner);

        if (planLocal.getParnters() == null)
            planLocal.setParnters("");

        String parnters = "";
        String[] ids = planLocal.getParnters().split(",");
        for (int i = 0; i < ids.length; i++) {
            if (!user_id.equals(ids[i])) {
                parnters = parnters + "," + ids[i];
            }
        }
        parnters = parnters.replaceFirst(",", "");
        int type = 0;
        if (parnters.equals("")) {
            type = 0;
        } else {
            type = 1;
        }

        /**
         *  对方同意加入之后更新这条计划的type为1
         *  将对方加入到自己计划的parnter中
         */
        Plan plan = new Plan();
        plan.setPlan_id(Long.valueOf(planId));
        plan.setPlan_type(type);
        plan.setParnters(parnters);

        planAndTaskService.updateTypeIdForPLan(plan);
        return null;
    }

    private void updateLastEditTime(long plan_id) {
        Plan plan = new Plan();
        plan.setPlan_id(plan_id);
        /**
         * 获取系统时间
         */
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        plan.setLast_edit_time(df.format(new Date()));
        planAndTaskService.updatePlanLastEditTime(plan);
    }
}